package com.common.utils;

import javax.servlet.http.HttpServletRequest;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

/**
 * Spring 统一日志处理实现类
 * @date 2009-5-8
 * @author davexin
 *
 */
public class LogInterceptorSpring implements MethodInterceptor
{

	public Object invoke(MethodInvocation invocation)
			//throws Throwable
	{
		Logger log = Logger.getLogger(invocation.getClass());
		try{
			//log.error("------Log By davexin Interceptor Start-----------------------------------------------------------------------------");
			StringBuffer sb = new StringBuffer();
			long threadid = Thread.currentThread().getId();
			log.error("------$$$$$$业务方法拦截器$$$$$$开始拦截线程"+threadid+"START>>>>>>"+invocation.getMethod()+"------");// 方法前的操作
			Object[] args = invocation.getArguments();
			if(args!=null){
				for (int i=0; i<args.length;i++) {
					sb.append(i + "=" + args[i].toString()+ "; ");
					if (args[i] instanceof HttpServletRequest) {
						HttpServletRequest request = (HttpServletRequest) args[i];
						//curUser = (T_user_detail) request.getSession().getAttribute("FREE_CURRENT_USER");
						String username = (String) request.getSession().getAttribute("FREE_CURRENT_USER");
						log.error("------spring拦截到用户session名字="+username);
					}
				}
			}
			//invocation.getClass().getDeclaredClasses().toString();
			//invocation.getMethod().getName();
			log.error("------$$$$$$业务方法拦截器$$$方法执行前截取参数及值,线程"+threadid+"参数:"+sb.toString()+";------");

			Object obj = invocation.proceed(); // 执行需要Log的方法
			log.error("------$$$$$$业务方法拦截器$$$方法执行后，拦截器拦截取参数及值,线程"+threadid+"返回对象:"+obj.getClass().getName().toString()+";值:"+obj.toString()+"------" );
			log.error("------$$$$$$业务方法拦截器$$$$$$结束拦截线程"+threadid+"END>>>>>>" + invocation.getMethod()+"------" );// 方法后的操作

			//log.error("------Log By davexin Interceptor End-------------------------------------------------------------------------------");

			return obj;
		}catch(Exception e){
			e.printStackTrace();
			log.error(e);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}
}
